package com.max.sys.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.max.common.controller.BaseController;
import com.max.core.shiro.token.manager.TokenManager;
import com.max.sys.domain.BSysUser;
import com.max.utils.ResponseData;

@Controller
public class LoginController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping("login")
	public String login(HttpServletRequest request, Model model) {
		String url = request.getRequestURL().toString();
		log.debug(url);
		String frowardUrl = (String) request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE);
		log.debug(frowardUrl);
		model.addAttribute("errorMsg",request.getParameter("errorMsg"));
		model.addAttribute("userName",request.getParameter("userName"));
		return "login";
	}

	@RequestMapping(value = "cas", method = RequestMethod.POST)
	public String cas(HttpServletRequest request, Model model, BSysUser user,RedirectAttributes redirect) {
		String url = request.getRequestURL().toString();
		log.debug(url);
		String frowardUrl = "/login";
		try {
			user = TokenManager.login(user, false);
			// 获取跳转登录页面之前的页面地址
			SavedRequest savedRequest = WebUtils.getSavedRequest(request);
			if (savedRequest != null) {
				frowardUrl = savedRequest.getRequestUrl();
				// 项目名称
				String contextPath = request.getContextPath();
				// 去掉项目路径
				frowardUrl = frowardUrl.replace(contextPath, "");
			}else {
				frowardUrl = "success";
			}
			log.debug("登录成功！");
		} catch (IncorrectCredentialsException e) {
			redirect.addAttribute("userName", user.getUserName());
			redirect.addAttribute("errorMsg", "密码错误");
		}catch (DisabledAccountException e){
			redirect.addAttribute("userName", user.getUserName());
			redirect.addAttribute("errorMsg", "账户被禁止登录");
		} catch (Exception e) {
			log.debug("登录失败！");
			e.printStackTrace();
		}
		return "redirect:" + frowardUrl;
	}

	@RequestMapping("success")
	public String success(HttpServletRequest request, Model model) {
		model.addAttribute("user", SecurityUtils.getSubject().getPrincipal());
		return "success";
	}

	@RequestMapping("verifyCode")
	@ResponseBody
	public ResponseData verifyCode(@RequestParam(required = true) String code) {
		try {
			String sessionCode = SecurityUtils.getSubject().getSession().getAttribute("validateCode").toString();
			if (code.equals(sessionCode)) {
				return operateSucess();
			}
		} catch (InvalidSessionException e) {
			e.printStackTrace();
			return operateFailed("验证码校验异常："+e.getMessage());
		}
		return operateFailed("验证码错误！");
	}
}
